<template>
  <view class="container">
    <view class="code-inputs">
      <!-- 小程序不支持双向数据绑定，天坑，uniapp编译双向绑定到小程序会报错 -->
      <div v-for="(item, index) in codeInputs.length" :key="index">
        <input
          @input.stop="handleInput"
          required
          type="number"
          maxlength="1"
          :focus="currentFocus === index"
          :value="codeInputs[index]"
          class="code-input"
          :data-index="index"
          @focus.stop
        />
      </div>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useMemberStore } from '@/stores'
import { loginRegisterCodeApi } from '@/services/loginApi'
const memberStore = useMemberStore()
// 定义输入列表,只能写入四个数字
const codeInputs = ref<number[] | string[]>(['', '', '', ''])
const currentFocus = ref(0)
// 计算属性，判断是否所有输入都已完成，如果没有空了，就认为是完成了
const isComplete = computed(() => {
  return codeInputs.value.every((input) => input !== '')
})
// 发送请求校验
const sendVerificationCode = async () => {
  const code = codeInputs.value.join('')
  const res = await loginRegisterCodeApi(memberStore.profile!.telephone!, code)
  if (res.statusCode === 200) {
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })
    console.log(res.data)
    memberStore.setNickname(res.data?.nickname!)
    memberStore.setToken(res.token!)
    memberStore.setIcon(res.data?.icon!)
    memberStore.setTelephone(res.data!.telephone!)
    memberStore.setIdentity(res.data!.identity!)
    memberStore.updateBalance(res.data!.balance!)
    memberStore.setidentityIcon(res.data!.identityIcon!)
    // 登录成功，跳转到首页
    // 登录成功，跳转到首页
    // 跳转到首页
    uni.switchTab({
      url: '/pages/index/index',
    })
  } else {
    uni.showToast({
      title: '登录失败',
      icon: 'none',
    })
  }
}
// 输入触发
const add = (index: number, e: UniHelper.EventTarget) => {
  codeInputs.value[index] = e.detail.value
  // 确保输入为单个数字,只截取一个数字
  // 自动跳转到下一个输入框
  if ((codeInputs.value[index] || codeInputs.value[index] != '') && index < 3) {
    console.log('跳转到下一个')
    console.log(codeInputs.value[index])
    currentFocus.value = index + 1
  }
  console.log('继续执行')
  // 检查是否所有输入都已完成
  if (isComplete.value) {
    // 输入完成发送验证码请求
    sendVerificationCode()
  }
}
// 删除触发
const del = (index: number, e: UniHelper.EventTarget) => {
  codeInputs.value[index] = ''
}
// 处理input事件
const handleInput = (e: UniHelper.EventTarget) => {
  const index = e.currentTarget!.dataset!.index
  console.log(e)
  console.log(e.detail.keyCode)
  // 判断是写入还是删除，删除keycode是8
  if (e.detail.keyCode === 8) {
    // 处理退格键
    del(index, e)
  } else {
    // 处理其他输入
    add(index, e)
  }
}
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.code-inputs {
  display: flex;
  gap: 20rpx;
}

.code-input {
  width: 80rpx;
  height: 80rpx;
  text-align: center;
  font-size: 40rpx;
  border: 2rpx solid #ccc;
  border-radius: 8rpx;
}
</style>
